package com.keyrus.user.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.keyrus.user.pojo.KomsResult;
import com.keyrus.user.pojo.User;
import com.keyrus.user.service.KomsUserService;

/**
 * 用户Controller
 *
 * @author David
 * @create 2018-10-24 19:57
 */

@RestController
public class KomsUserController
{
    private static final Logger LOG = LogManager.getLogger(KomsUserController.class);

    @Autowired
    private KomsUserService userService;

    /**
     * 根据id找到用户
     * @param token    用户uuid
     * @return      用户对象
     */
    @GetMapping("/info")
    @ResponseBody
    public KomsResult showUser(@RequestParam String token)
    {
        final User user = userService.getUserByUuid(token);

        if (user == null)
        {
            return new KomsResult(false, "查找失败，用户不存在", "");
        }
        else
        {
            final JSONObject data = new JSONObject();
            data.put("token", user.getUuid());
            data.put("id", user.getId());
            data.put("name", user.getName());
            data.put("roles", user.getRoles());

            return new KomsResult(true, "查找成功", data);
        }
    }

    /**
     * 根据用户名密码生成用户
     * @param id  id
     * @param name  用户名
     * @param password  密码
     * @return  uuid
     */
    @RequestMapping("/create")
    @ResponseBody
    public KomsResult generateUser(@RequestParam String id, @RequestParam String name, @RequestParam String password)
    {
        return userService.generateUser(id, name, password);
    }

    /**
     * 登录
     * @param userDTO    用户入参dto
     * @return  成功失败
     */
    @PostMapping("/login")
    @ResponseBody
    public KomsResult userLogin(@RequestBody User userDTO)
    {
        final User user = userService.getUserById(userDTO.getId());
        if (user == null)
        {
            return new KomsResult(false, "用户不存在, 请注册", "") ;
        }
        else
        {
            //校验账号密码，成功返回token
            if (user.getId().equals(userDTO.getId()) && user.getPassword().equals(userDTO.getPassword()))
            {
                if (StringUtils.isBlank(user.getUuid()))
                {
                    final String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                    user.setUuid(uuid);
                    if (userService.saveUser(user))
                    {
                        return new KomsResult(true, "登录成功", new JSONObject(){{put("token", uuid);}}) ;
                    }
                    else
                    {
                        return new KomsResult(true, "登录失败，请重新尝试", "") ;
                    }
                }
                else
                {
                    return new KomsResult(true, "登录成功", new JSONObject(){{put("token", user.getUuid());}}) ;
                }
            }
            else
            {
                return new KomsResult(false, "密码错误，请重新输入", "") ;
            }
        }
    }

    /**
     * 登出
     * @return  成功失败
     */
    @PostMapping("/logout")
    @ResponseBody
    public KomsResult userLogout(@RequestBody String token)
    {
        final User user = userService.getUserByUuid(token);
        if (user == null)
        {
            return new KomsResult(false, "查找不到用户，登出失败", "");
        }
        else
        {
            if (userService.clearUuid(user))
            {
                return new KomsResult(true, "登出成功", "");
            }
            return new KomsResult(false, "uuid清空失败，登出失败", "");
        }
    }

    /**
     * 检查是否登录
     * @param request   session
     * @return  成功失败
     */
    @Deprecated
    @RequestMapping("/isLogin")
    public String isLogin(HttpServletRequest request)
    {
        LOG.info("====================== get session : {}", request.getSession().getId());
        final User user = (User) request.getSession().getAttribute("userLogin");
        LOG.info("====================== user : {}", user);
        if (user == null)
        {
            return "用户没有登录";
        }
        else
        {
            return "登录的用户id为：" + user.getId() + " , 名字为：" + user.getName();
        }
    }
}
